<template>
	<view v-if="!loading" class="my">
		<view class="my-head flex">
			<view class="user-info">
				<image class="avatar" :src="userConfig.user.avatar ? userConfig.user.avatar : defaultAvatar " mode=""></image>
				<view class="user-con">
					<view class="user-name">你好，{{userConfig.user.nick || '有派用户'}}</view>
					<view class="user-tags">
						<view class="user-tag new" v-if="leaderId>0">团 长</view>
						<view class="user-tag new" v-if="franchisee_id>0">合伙人</view>
						<view class="user-tag new" v-if="hasShop">商 户</view>
						<view class="user-tag new" v-if="leaderId < 1 && franchisee_id < 1 && !hasShop">有派用户</view>
					</view>
				</view>
			</view>
			<view class="user-set flex">
				<image class="code" src="../../static/images/my-code.svg" mode="" @click="showCode"></image>
				<image class="code" src="../../static/images/set.svg" mode="" @click="toMylist({link: '../set/index'})"></image>
			</view>
		</view>
		<view class="my-data box flex" @click="toMylist({link: '../earnings/index'})">
			<view class="data-list">
				<view class="data-count">{{ userConfig.balance ? (userConfig.balance /100).toFixed(2) : 0}}</view>
				<view class="data-txt">账户余额</view>
			</view>
			<view class="data-list">
				<view class="data-count">{{userConfig.cashbacked ? (userConfig.cashbacked / 100).toFixed(2)  : 0}}</view>
				<view class="data-txt">已免单</view>
			</view>
			<view class="data-list">
				<view class="data-count">{{userConfig.cashback_orders || 0}}</view>
				<view class="data-txt">排队订单</view>
			</view>
		</view>
		<view class="my-order box">
			<view class="order-head flex">
				<view class="order-tit">我的订单</view>
				<view class="order-check" @click="checkOrder">
					<view class="check-tit">查看订单</view>
					<image class="arrow" src="../../static/images/arrow-r.svg" mode=""></image>
				</view>
			</view>
			<view class="order-status flex">
				<view v-for="item in orderStatus" :key="item.id" class="order-list" @click="checkOrder(item.id)">
					<uni-badge class="uni-badge-left-margin" :text="userConfig.order_count[item.id]" absolute="rightTop" size="small">
						<image :src="item.icon" class="order-list-icon"></image>
					</uni-badge>
					<view class="order-list-txt">{{item.name}}</view>
				</view>
			</view>
		</view>
		<template v-if="banners.length > 0">
			<view class="uni-margin-wrap">
				<image class="welfare" v-if="banners.length == 1" :src="banners[0].image" mode="" @click="toMylist(banners[0])"></image>
				<swiper class="swiper" v-else circular :indicator-dots="true" :autoplay="true" :interval="4000"
					:duration="500">
					<swiper-item v-for="item in banners" :key="item.id" >
						<img class="swiper-ad" :src="`${item.image}`" alt="" @click="toMylist(item)"/>
					</swiper-item>
				</swiper>
			</view>
		</template>
		<view class="my-list-box">
			<view v-for="item in myList" :key="item.id" class="my-list flex" @click="toMylist(item)">
				<view class="my-list-con">
					<image class="icon" :src="item.icon" mode=""></image>
					<view class="txt">{{item.name}}</view>
				</view>
				<image class="arrow" src="../../static/images/arrow-r.svg" mode=""></image>
			</view>
		</view>
		<l-painter ref="painter" :board="poster" :hidden="true"/>
	</view>
</template>

<script setup>
	import paying from '../../static/images/order-paying.svg';
	import sending from '../../static/images/order-sending.svg';
	import waiting from '../../static/images/order-waiting.svg';
	import refund from '../../static/images/order-refund.svg';
	import all from '../../static/images/order-all.svg';
	import earnings from '../../static/images/icon_balance.svg'
	import adress from '../../static/images/icon_address.svg';
	import invite from '../../static/images/invite.svg';
	import online from '../../static/images/icon_chat.svg';
	import question from '../../static/images/icon_qa.svg';
	import about from '../../static/images/icon_about.svg';
	import defaultAvatar from '../../static/images/avatar.svg';
	import leader from '../../static/images/icon_leader.svg';
	import franchisee from '../../static/images/icon_franchisee.svg';
	
	import { getUserDetail, indexAds } from '../../http/apis.js'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { ref } from 'vue'
	import { useMutations } from '../../store/hooks/useMutations';
	import { useGetters } from '../../store/hooks/useGetters';
	const { leaderId, franchisee_id, hasShop } = useGetters(['leaderId', 'franchisee_id', 'hasShop']);
	const { setCartBadge, setUser } = useMutations(['setUser', 'setCartBadge']);
	
	const orderStatus = ref([
		{ id: 1, name: '待付款', icon: paying},
		{ id: 2, name: '待发货',icon: sending},
		{ id: 3, name: '待收货',icon: waiting},
		{ id: 5, name: '售后',icon: refund},
		{ id: 0, name: '全部订单',icon: all},
	])
	const myList = ref([
		{ id: 1, name: '地址管理', icon: adress, link: '/personal/address/index'},
		{ id: 2, name: '我的收益',icon: earnings, link: '../earnings/index'},
		{ id: 3, name: '邀请好友',icon: invite, link: '/personal/invite/index'},
		{ id: 4, name: '在线客服',icon: online, link: '/personal/online/index'},
		{ id: 5, name: '常见问题',icon: question, link: '/personal/question/index'},
		{ id: 6, name: '关于我们',icon: about, link: '/personal/about/index?id=1'},
		// { id: 7, name: '团长收益',icon: leader, link: '../leader/index'},
		// { id: 8, name: '代理收益',icon: franchisee, link: '../franchisee/index'}
	]);
			
	onLoad(() => {
		getAds();
		if (leaderId > 0) {
			myList.push({ id: 7, name: '团长收益',icon: leader, link: '/personal/leader/index'})
		}
		if (franchisee_id > 0) {
			myList.push({ id: 8, name: '代理收益',icon: franchisee, link: '/personal/franchisee/index'})
		}
	})
	onShow(() => {
		getData();
		setCartBadge();
	})
	 // 广告配置
	const banners = ref([])
	const getAds = () => {
		indexAds({display: 4}).then(res => {
			banners.value = res;
		})
	}
	// 个人信息
	const loading = ref(true);
	const userConfig = ref(null)
	const getData = () => {
		getUserDetail().then(res => {
			loading.value = false;
			userConfig.value = res;
			setUser(res);
			// 用户没有完善资料，提示用户去完善
			if (res.accelerated_package !== 1 && !banners.value.some((item) => item.id === 99999)) {
				banners.value.unshift({id: 99999, image: 'https://files.youpaish.com/my-user-profile-ad.jpg', link: '../set/index'})
			}
			// UQRCode.make({
			// 	canvasId: 'qrcode',   // 切记canvasId 里边的内容需要跟canvas里边canvas-id="qrcode"的名字一样
			// 	componentInstance: this,
			// 	text: `https://www.youpaish.com/weapp/redirect?inviter=${res.user.id}`,  // 转成二维码的内容
			// 	size: 220, // 绘制大小，可根据自身需求可动态获取容器大小进行生成
			// 	margin: 10, // 二维码在canvas画布内的便宜量
			// 	backgroundColor: '#ffffff', // 二维码背景颜色
			// 	foregroundColor: '#000000', // 二维码颜色
			// 	fileType: 'jpg', // 二维码图片格式
			// 	errorCorrectLevel: UQRCode.errorCorrectLevel.H,
			// 	success: res => {
			// 		this.qrCodeImg = res // 此图片为base64格
			// 	},
			// })
		}).catch(res => {
			loading.value = false;
		})
	}
	const toMylist = (item) => {
		if (item.link) {
			uni.navigateTo({
				url: item.link
			})
		}
	}
	const checkOrder = (type) => {
		uni.navigateTo({
			url: '/pages/order/index?status=' + type
		})
	}
	
	// 邀请码分享
	const poster = ref(null);
	const painter = ref(null);
	const showCode = () => {
		let url = `https://www.youpaish.com/weapp/redirect?inviter=${userConfig.value.user.id}`;
		poster.value = {
			"css": {
				"width": "402rpx",
				"height": "536rpx",
				"paddingTop": '44rpx',
				"boxSizing": 'border-box',
				"background": "transparent"
			},
			"views": [{
				"type": "image",
				"src": "https://files.youpaish.com/user-share-qrcode-img.png",
				"css": {
					"width": "402rpx",
					"height": "536rpx",
					"background": "transparent",
					"position": "fixed",
					"borderRadius": '16rpx',
					"top": "0",
					"left": "0",
					"zIndex": -1,	
				}
			},{
				type: 'qrcode',
				text: url,
				css: {
					width: '95rpx',
					height: '95rpx',
					padding: '10rpx',
					boxSizing: 'border-box',
					color: '#000',
					backgroundColor: '#fff',
					margin: '290rpx 150rpx 0 162rpx',
					borderRadius: '8rpx',
				}
			}]
		}
		
		painter && painter.value.canvasToTempFilePathSync({
		  fileType: "png",
		  // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
		  pathType: 'url',
		  quality: 1,
		  success: (res) => {
			showSahreMenu(res.tempFilePath)
		  },
		});
	}
	const showSahreMenu = (url) => {
		uni.showShareImageMenu({
			path: url,
			success:(req) => {
				console.log(req);
			}
		})
	}
	
	// 旧版保存图片方法
	const qrCodeImg = ref('');
	const save = () => {
		uni.getSetting({ //获取用户的当前设置
			success: (res) => {
				if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
					aveImageToPhotosAlbum();
				} else {
					uni.authorize({ //如果没有授权，向用户发起请求
						scope: 'scope.writePhotosAlbum',
						success: () => {
							aveImageToPhotosAlbum();
						},
						fail: () => {
							// 提示
							uni.showToast({
								title: "请打开保存相册权限，再点击保存到手机",
								icon: "none",
								duration: 1500
							});
							setTimeout(() => {
								uni.openSetting({ //调起客户端小程序设置界面,让用户开启访问相册
									success: (res2) => {
										
									}
								});
							}, 1500);
						}
					})
				}
			}
		})
	}
	const aveImageToPhotosAlbum = () => {
		let base64 = qrCodeImg.value.replace(/^data:image\/\w+;base64,/, ""); //去掉data:image/png;base64,
		let filePath = wx.env.USER_DATA_PATH + '/ph_fit_qrcode.png';    //   路径文件名
		uni.getFileSystemManager().writeFile({  // 获取全局唯一的文件管理器
			filePath: filePath, //创建一个临时文件名
			data: base64, //写入的文本或二进制数据
			encoding: 'base64', //写入当前文件的字符编码
			success: res => {
				uni.saveImageToPhotosAlbum({    // 保存图片到系统相册
					filePath: filePath,
					success: function(res2) {
						uni.hideLoading();
						uni.showToast({
							title: '保存成功',
							icon: "none",
						})
					},
					fail: function(err) {
						uni.hideLoading();
						// console.log(err.errMsg);
					}
				})
			},
			fail: err => {
				uni.hideLoading();
			}
		})
	}
</script>

<style lang="scss" scoped>
	.flex {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.box {
		background-color: #ffffff;
		border-radius: 16rpx;
		box-sizing: border-box;
	}
	.arrow {
		width: 12rpx;
		height: 24rpx;
	}
	#qrcode {
		position: absolute;
		right: 2000rpx;
		bottom: 2000rpx;
		width: 2000rpx;
		height: 2000rpx;
	}
	.my {
		width: 100%;
		min-height: 100vh;
		padding: 160rpx 24rpx 50rpx 24rpx;
		box-sizing: border-box;
		background: linear-gradient(180deg, #FBDF4F -3%, rgba(248, 250, 253, 0.77) 27%, #F8FAFD 100%);
		position: relative;
		.my-title {
			width: 100%;
			height: 60rpx;
			line-height: 60rpx;
			position: sticky;
			text-align: center;
			font-size: #2e2e2e;
			font-size: 28rpx;
			margin-bottom: 34rpx;
		}
		.my-head {
			width: 100%;
			height: 140rpx;
			align-items: flex-start;
			.user-info {
				display: flex;
				align-items: center;
				height: 100%;
				flex: 1;
				overflow: auto;
				.avatar {
					width: 140rpx;
					height: 140rpx;
					border-radius: 50%;
					margin-right: 30rpx;
				}
				.user-con {
					height: 100%;
					padding: 20rpx 0;
					box-sizing: border-box;
					overflow: auto;
					flex: 1;
					.user-name {
						color: #000000;
						font-size: 36rpx;
						lighting-color: 48rpx;
						margin-bottom: 10rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
					.user-tag {
						height: 40rpx;
						line-height: 40rpx;
						border-radius: 20rpx;
						margin-right: 10rpx;
						text-align: center;
						background: #EDD24F;
						display: inline-block;
						padding: 0 24rpx;
						&.new {
							color: #5F4200;
							font-size: 28rpx;
						}
					}
				}
			}
			.user-set {
				padding-top: 28rpx;
				box-sizing: border-box;
				width: 100rpx;
				.code {
					width: 38rpx;
					height: 38rpx;
				}
			}
		}
		.my-data {
			margin-top: 30rpx;
			width: 100%;
			display: flex;
			padding: 26rpx 69rpx 30rpx 69rpx;
			.data-list {
				width: 145rpx;
				.data-txt {
					color: #969799;
					font-size: 28rpx;
					line-height: 40rpx;
					text-align: center;
				}
				.data-count {
					color: #2E2E2E;
					font-size: 40rpx;
					line-height: 60rpx;
					font-weight: bold;
					text-align: center;
				}
			}
		}
		.my-order {
			width: 100%;
			padding: 24rpx 25rpx 24rpx 25rpx;
			margin-top: 24rpx;
			.order-head {
				width: 100%;
				height: 56rpx;
				.order-tit {
					color: #2E2E2E;
					font-size: 36rpx;
					font-weight: bold;
					line-height: 56rpx;
				}
				.order-check {
					display: flex;
					align-items: center;
					.check-tit {
						color: #969799;
						font-size: 24rpx;
						margin-right: 12rpx;
					}
					
				}
			}
			.order-status {
				width: 100%;
				margin-top: 39rpx;
				.order-list {
					width: 110rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					.order-list-icon {
						width: 52rpx;
						height: 52rpx;
					}
					.order-list-txt {
						color: #2E2E2E;
						font-size: 24rpx;
						line-height: 52rpx;
						text-align: center;
					}
				}
			}
		}
		.uni-margin-wrap {
			width: 100%;
			height: 164rpx;
			margin-top: 30rpx;
			.swiper {
				width: 100%;
				height: 164rpx;
				.swiper-ad {
					width: 100%;
					height: 164rpx;
					border-radius: 8rpx;
				}
			}
			.welfare{
				width: 100%;
				height: 164rpx;
				border-radius: 8rpx;
			}
		}
		.my-list-box {
			width: 100%;
			margin-top: 60rpx;
		}
		.my-list {
			height: 48rpx;
			margin-bottom: 48rpx;
			width: 100%;
			padding-right: 27rpx;
			box-sizing: border-box;
			.my-list-con {
				display: flex;
				align-items: center;
				height: 40rpx;
				.icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 20rpx;
				}
				.txt {
					color: #2e2e2e;
					font-size: 32rpx;
					line-height: 40rpx;
				}
			}
		}
	}
	.code-popup {
		width: 100%;
		height: 620rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		.code {
			width: 460rpx;
			height: 460rpx;
		}
		.code-btn {
			margin-top: 40rpx;
			height: 72rpx;
			width: 360rpx;
			line-height: 40rpx;
			padding: 16rpx 44rpx;
			box-sizing: border-box;
			border-radius: 36rpx;
			background: linear-gradient(113deg, #FADF5D 18%, #F7D35D 81%);
			text-align: center;
			color: #30240A;
			font-size: 28rpx;
		}
	}
</style>
